<template>
  <div
    v-loading="loading"
    class="monthPlanAdd"
  >
    <b-table
      ref="table"
      :columns="columns"
      :scroll="{ x: 1300 }"
      :request="loadData"
      :export-config="{ use: true,select: '物资需用计划表',all: '物资需用计划表', customColumns: customColumns}"
    >
            <template  v-if="state !== 3" slot="prefix" slot-scope="ref">
                <a-button type="primary" @click="openDialog()">添加行</a-button>
                <a-button @click="ref.delete(delFuc, delEnd)">删除行</a-button>
            </template>
            <template slot="suffix" v-if="state !== 3">
                <!-- v-btn-permission="'lcm_003_exp_05'" -->
              <excel ref="exportBtn"
                file-name="物资需用计划表"
                content-title="物资需用计划表"
                is-click-generate="false"
              >
                <a-button
                  slot="excelBtn"
                  type="primary"
                  icon="cloud-download"
                  :loading="addLoading"
                  @click="openDialog(downloadApi)"
                >
                  标准模板下载
                </a-button>
              </excel>
              <ExcelImportButton
                :loading="loadingImport"
                icon="import"
                button-text="批量导入"
                @handleSubmit="handleImport"
              />
            </template>

            <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
            <template
                v-for="col in ['orgName','num', 'price', 'planDate','analysisIdentify','solutions']"
                :slot="col"
                slot-scope="text, record, index">
                <template v-if="state !== 3">
                    <span v-if="col === 'analysisIdentify'" class="requiredFormItem">
                      <a-select
                          @change="rowChange(record)"
                          v-model="record[col]">
                          <a-select-option :value="item.id" v-for="item in optionArr" :key="item.id">
                              {{ item.name }}
                          </a-select-option>
                      </a-select>
                    </span>
                    <a-date-picker
                        class="requiredFormItem"
                        v-else-if="col === 'planDate'"
                        type="date"
                        format="YYYY-MM-DD"
                        valueFormat="YYYY-MM-DD"
                        @change="rowChange(record)"
                        v-model="record[col]" />
                    <b-input-number
                        class="requiredFormItem"
                        :min="0"
                        :precision="3"
                        @blur="rowChange(record)"
                        v-else-if="col === 'num'"
                        v-model="record[col]" />
                    <b-input-number
                        class="requiredFormItem"
                        :min="0"
                        :precision="2"
                        @blur="rowChange(record)"
                        v-else-if="col === 'price'"
                        v-model="record[col]" />
                    <b-input
                        v-else
                        @blur="rowChange(record)"
                        v-model="record[col]"
                        :showTipLength="8"
                        :disabled="col === 'orgName' || col === 'projectCode'" />
                </template>
                <template v-else>
                    {{ col === 'analysisIdentify' ? record.analysisIdentifyStr : text }}
                </template>
            </template>
        </b-table>
        <material-list-and-dir
          ref="detailDialog"
          @createList="createList"
        />
    </div>
</template>
<script>
import { selectOption } from '@/api/material/goods/goods'
import { planDetailList, planDetailListDel, planListAddList, planDetailEdit, tenderPlanExcel } from '@/api/material/procurement/plan'
import { columns } from './insideModel'
import { themeChoose } from '@/mixin/mixin'
import { pubOrgList } from '@/api/material/public/public'
import cloudBuildNetworkApi from '@/api/legal/branchContract/cloudBuildNetwork'
import moment from 'moment'

export default {
  name: "RebarPlan",
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        },
        extraRef: {
            type: Object,
            default: null
        }
    },
    data() {
        return {
            loadData: params => planDetailList({ ...params, tenderPlanId: this.id }),
            delFuc: planDetailListDel,
            downloadApi: tenderPlanExcel,
            loading: false,
            loadingImport: false,
            addLoading: false,
            queryParam: {},
            columns: columns,
            customColumns: [],
            optionArr: [],
            orgName: '',
            rules: {
                orgName: { message: '单位名称不能为空', trigger: 'blur' },
                num: { message: '数量不能为空', trigger: 'blur' },
                price: { message: '概算金额不能为空', trigger: 'blur' },
                planDate: { message: '计划招标时间不能为空', trigger: 'blur' },
                analysisIdentify: { message: '盈亏分析辨识不能为空', trigger: 'blur' }
            },
            editingIndex: null,
        }
    },
    watch: {},
    created() {
      this.getCustomColumns()
    },
    mounted: function() {
        this.getOption()
        if (this.state === 3) {
            this.editingIndex = null
        }
        this.getOrg();
    },
    methods: {
        getCustomColumns() {
          const list = [...this.columns];
          this.customColumns = list.map((item, index) => {
            const title = item.title;
            const dataIndex = item.dataIndex;
            if (dataIndex == 'analysisIdentify') {
              return {
                title,
                dataIndex: 'analysisIdentifyStr'
              }
            } else {
              return {
                title,
                dataIndex
              }
            }
          })
        },
        delEnd() {
          if (!this.$refs.table.tableData.length) {
            this.$refs.table.getData(null, true);
          };
        },
        rowChange(row) {
          this.save(row);
        },
        async getOrg() {
            let res = await pubOrgList({ id: this.$userInfo().orgId })
            if (res.status === this.SUCCESS_CODE) {
                this.orgName = res.data.list[0].name
            }
        },
        async createList(selectRow) {
          const params = [];
          selectRow.map((item, index) => {
            params.push({
                executeType: '0',
                materialName: item.name,
                materialCode: item.code,
                materialModel: item.specificationModel,
                unit: item.unitId,
                tenderPlanId: this.id,
                orgName: this.extraRef && this.extraRef.getLabel(),
                num: null,
                price: '',
                planDate: '',
                analysisIdentify: null,
                solutions: null,
                materialId: item.id
            })
          })
          this.loading = true
          let res = await planListAddList(params)
          if (res.code === this.SUCCESS_CODE) {
              this.$message.success('添加成功')
              this.cancel()
          }
          this.loading = false
        },
        async getOption() {
            let res = await selectOption({ type: 0 })
            if (res.code === this.SUCCESS_CODE) {
                this.optionArr = res.data
            }
        },
        async openDialog(downloadApi) {
            let checkedData = this.$refs.table.tableData;
            if (this.$refs.table.totalSize > 10) {
              this.addLoading = true;
              let res = await planDetailList({
                pageSize: this.$refs.table.totalSize,
                pageNo: 1,
                purchaseApplyId: this.id,
              })
              
              checkedData = res.data;
              this.addLoading = false
            }
            if (downloadApi){
              const fileName = "物资招标计划模板_" + moment(new Date()).format('YYYY-MM-DD') + ".xlsx";
              this.$refs.detailDialog.download(checkedData,downloadApi,fileName)
            }else {
              this.$refs.detailDialog.open(checkedData)
            }
        },
        async save(row) {
          let res = await planDetailEdit(row)
          if (res.code !== 200) this.$noticeWarning(res.message)
        },

        cancel() {
            this.editingIndex = null
            this.$refs.table.getData(null , true)
        },
        /**
         * 导入
         */
        async handleImport(list) {
          try {
            if (this.loadingImport) return
            this.loadingImport = true;
            // 读取到的日期时间会被解析会数字，因此这里将其转换回YYYY-MM-DD格式
            const formatDate = (numb, format) => {
              const time = new Date((numb - 1) * 24 * 3600000 + 1)
              time.setYear(time.getFullYear() - 70)
              const year = time.getFullYear() + ''
              const month = time.getMonth() + 1 + ''
              const date = time.getDate() - 1 + ''
              if (format && format.length === 1) {
                return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
              }
              return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
            }
            const columns = [
              {title: '物料名称',dataIndex: 'materialName'},
              {title: '物料编码',dataIndex: 'materialCode'},
              {title: '规格型号',dataIndex: 'materialModel'},
              {title: '计量单位',dataIndex: 'unit'},
              {title: '*数量',dataIndex: 'num'},
              {title: '*概算金额',dataIndex: 'price'},
              {title: '*计划招标时间',dataIndex: 'planDate'},
              {title: '*盈亏分析辨识',dataIndex: 'analysisIdentifyName'},
              {title: '*采取措施',dataIndex: 'solutions'}
            ]
            const paramsList = [];
            const err = [];
            for (let i = 0; i < list.length; i ++) {
              const item = list[i];
              const resultItem = {}
              for (const key in item) {
                const target = columns.find((column) => column.title === key)
                if (target) {
                  if (target.title === '计划招标时间') {
                    resultItem[target.dataIndex] = typeof item[key] == 'number' ? formatDate(item[key], '-') : moment(new Date(item[key])).format('YYYY-MM-DD');
                  } else {
                    resultItem[target.dataIndex] = item[key]
                  }
                }
              }
              resultItem.tenderPlanId = this.id;
              resultItem.orgName = this.extraRef && this.extraRef.getLabel();
              resultItem.executeType = '1';
              const rightAnaly = this.optionArr.some((e) => resultItem.analysisIdentifyName == e.name)
              if (!rightAnaly) {
                err.push(i + 1);
              }
              paramsList.push(resultItem)
            }
            if (err.length) {
              const msg = err.join('、');
              this.$notification['error']({
                message: '提示',
                description: `请正确选择第${msg}行盈亏分析辨识！`,
                duration: 4
              })
              this.loadingImport = false;
              return;
            }
            if (!paramsList.length) {
              this.$message.warning('请录入导入数据');
              this.loadingImport = false;
              return;
            }
            planListAddList(paramsList).then(res => {
              this.loadingImport = false;
              if ((res.code === 200) || (res.data?.code === 200)) {
                  this.$message.success('导入成功')
                  this.cancel()
              }
            }).catch(() => {
              this.loadingImport = false;
            })
          } catch (e) {
            this.loadingImport = false
          }
          
        }
    }
}
</script>
